package fr.inria.arles.temperatureManagement;

import static fr.inria.arles.temperatureManagement.Constants.PROP_FILE;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Properties;

/**
 * A Utility Class providing methods to convert between Strings and String
 * arrays and to handle command line arguments.
 */
public class Utility {

	/** The String SEPERATOR. */
	private static final String SEPERATOR = "_";

	/**
	 * Encodes a String array into one String.
	 * 
	 * @param args
	 *            the string array to be encoded
	 * @return the encoded string
	 */
	public static String encode(String... args) {
		int i;
		StringBuilder str = new StringBuilder();
		for (i = 0; i < args.length - 1; i++) {
			str.append(args[i]);
			str.append(SEPERATOR);
		}
		str.append(args[i] + "");
		return str.toString();
	}

	/**
	 * Decodes an encoded String to a String array
	 * 
	 * @param str
	 *            the string to be decoded
	 * @return the decoded string array
	 */
	public static String[] decode(String str) {
		return str.split(SEPERATOR);
	}

	/**
	 * Processes command line arguments to set properties
	 * 
	 * @param arg
	 *            the command line argument
	 * @param prop
	 *            the name of the property being set
	 * @param val
	 *            the value of the property being set
	 * @param properties
	 *            the application properties
	 * @return the decoded string array
	 */
	public static boolean processArg(Properties properties, String arg,
			String prop, String val) {
		if (arg.substring(1).equalsIgnoreCase(prop)) {
			properties.setProperty(prop, val);
			System.out.println(prop + " set to " + val);
			return true;
		} else {
			return false;
		}
	}

	public static void loadProperties(Properties properties, String filename) {
		try {
			properties.load(new FileInputStream(filename));
			System.out.println("Propeties loaded from file:" + filename);
		} catch (Exception e) {
			System.out.println("Unable to load properties from file:"
					+ filename);
		}
	}

}
